import mongoose from 'mongoose';
import { MongoConnectParam } from '../definitions/common';
import { MONGO_AUTH, MONGO_USER, MONGO_PASS, MONGO_DBNAME, MONGO_URL } from '../config';

/**
 * 连接 mongo 数据库
 */
export default async function connectMongo() {
  mongoose.Promise = global.Promise;
  mongoose.connection.on('error', console.error.bind(console, '连接数据库失败'));
  let connectParams: MongoConnectParam = { useNewUrlParser: true, useUnifiedTopology: true };
  if (MONGO_AUTH) {
    connectParams = {
      user: MONGO_USER,
      pass: MONGO_PASS,
      auth: { authdb: MONGO_DBNAME, authMechanism: 'MONGODB-CR' },
      useNewUrlParser: true,
      useUnifiedTopology: true
    };
  }
  mongoose.set('useCreateIndex', true);
  return await mongoose.connect(MONGO_URL, connectParams as any);
}
